package kassiopeia.commons.util;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;

import org.apache.log4j.Logger;

public final class JmsUtils {

    private static final Logger logger = Logger.getLogger(JmsUtils.class);

    private JmsUtils() {}

    public static <T> T convertObjectMessage(Message message, Class<T> messageType) {
        if((message == null) || !(message instanceof ObjectMessage)) {
            return null;
        }

        ObjectMessage objectMessage = (ObjectMessage)message;

        return unpackObjectMessage(objectMessage, messageType);
    }

    private static <T> T unpackObjectMessage(ObjectMessage message, Class<T> messageType) {
        try {
            Object object = message.getObject();
            if(messageType.isInstance(object)) {
                return messageType.cast(object);
            }
        } catch (JMSException exception) {
            logger.error("Can't unpack JMS ObjectMessage",exception);
        }

        return null;
    }
}
